// component/order/order.js
var app = getApp()
Component({
  options: {
    addGlobalClass: true,
  },
  /**
   * 组件的属性列表
   */
  properties: {
    type:{
      type:String,
      value:'',
      observer: function(newVal, oldVal){
        console.log('type',newVal)
        if(newVal&&newVal!=oldVal){
          this.setData({
            orderfenlei:newVal
          })
          this.requestOrder()
        }
        return newVal;
      }
    },
    isReload:{
      type:Boolean,
      value: false,
      observer: function(newVal, oldVal){
        if(newVal){
          this.onPullDownRefresh();
        }
        return newVal;
      }
    },
    isReachBottom:{
      type:Boolean,
      value: false,
      observer: function(newVal, oldVal){
        console.log(newVal);
        if(newVal){
          this.onReachBottom();
        }
        return newVal;
      }
    },
  },

  /**
   * 组件的初始数据
   */
  data: {
    isShowModal: false,
    modalType: '',
    orderfenlei: 'all',
    showLoading: true,
    noMoretip: false,
    page: 0,
    tkOrderid: "",
    tkMoney: "",
    tkReason: "",
    tkContact: "",
    navH: app.globalData.navHeight,
    curTid:'',
    isShowAllGoods:false
  },

  lifetimes: {
    attached: function() {
      // 在组件实例进入页面节点树时执行
      var that = this;
      wx.getStorage({
        key: 'shopInfoname',
        success: function (res) {
          that.setData({
            shopname: res.data
          })
        }
      })
      that.requestOrder();
    },
    detached: function() {
      // 在组件实例被从页面节点树移除时执行
    },
  },

  pageLifetimes: {
    // 组件所在页面的生命周期函数
    show: function () { 
      console.log('展示订单')
      app.setNavtitle('我的订单');
      var that = this;
      if (!app.globalData.plumSession) {
      app.wechatSq(that);
      }
      that.setData({
        customerService: app.globalData.customerService
      })
      app.setCartnum();//更新购物车数量
      that.requestOrder();
    },
    hide: function () { },
  },

  /**
   * 组件的方法列表
   */
  methods: {
    // 折叠商品切换显示
    toggleGoods(e){
      let i = e.currentTarget.dataset.index;
      this.data.orderList[i].isShowAllGoods = !this.data.orderList[i].isShowAllGoods;
      this.setData({
        [`orderList[${i}].isShowAllGoods`]:this.data.orderList[i].isShowAllGoods
      })
    },
    callPhone(e){
      let phone = e.currentTarget.dataset.phone;
      wx.makePhoneCall({
        phoneNumber: phone,
      })
    },
    requestOrder:function(){
      var that = this;
      var page = that.data.page;
      var status = that.data.orderfenlei;
      var verify_type = '';
      if(status == 'hadpay1'){  //待使用特殊处理
        status = status.slice(0,-1);
        verify_type = 'code';
      }
      wx.request({
        url: app.globalData.requestUrl,
        data: {
          map: 'applet_order_list',
          status: status,
          page: page,
          verify_type
        },
        success: function (res) {
          console.log(page);
          if (res.data.ec == 200) {
            var allArr = [];
            var initArr = that.data.orderList;
            var curArr = res.data.data;
            var lastPageLength = curArr.length;
            if (page > 0) {
              allArr = initArr.concat(curArr);
            } else {
              allArr = res.data.data;
            }
            // let arr = allArr[0].goods.concat();    //测试数据
            // allArr[0].goods = allArr[0].goods.concat(arr);
            that.setData({
              orderList: allArr
            })
            if (lastPageLength < 10) {
              that.setData({
                noMoretip: true,
                showLoading: false
              });
            }
            console.log(that.data.orderList);
          } else {
            console.log(page);
            if (page <= 0) {
              that.setData({
                orderList: [],
                showLoading: false
              })
            } else {
              that.setData({
                noMoretip: true,
                showLoading: false
              });
            }
            console.log(res.data);
          }
        },
        complete: function () {
          wx.stopPullDownRefresh();
          that.triggerEvent('changereload', {isReload:false}) //下拉刷新结束，刷新页面组件状态
          that.triggerEvent('reachbottomchange', {isReachBottom:false}) //触底结束，刷新页面组件状态
        }
      });
    },
    orderDetail: function (e) {
      var orderId = e.currentTarget.dataset.orderid;
      wx.navigateTo({
        url: '/subpages1/orderDetail/orderDetail?orderid=' + orderId
      })
    },
    chooseFenlei: function (e) {
      var that = this;
      var fenlei = e.target.dataset.fenlei;
      that.setData({
        orderList:null,
        orderfenlei: fenlei,
        page: 0,
        noMoretip: false,
        showLoading: true
      })
      that.requestOrder();
    },
    onPullDownRefresh: function () {
      var that = this;
      that.setData({
        page: 0,
        noMoretip: false,
        showLoading: true
      });
      that.requestOrder();
      console.log("下拉刷新");
    },
    onReachBottom: function () {
      var that = this;
      console.log("到达页面底部")
      var isMore = that.data.noMoretip;
      var page = that.data.page;
      page++;
      that.setData({
        page: page
      });
      if (isMore) {
        console.log("已完成或正在加载");
      } else {
        that.requestOrder();
      }
    },
    cancelOrder: function (e) {
      var that = this;
      var orderId = e.target.dataset.id;
      wx.showModal({
        title: '',
        cancelText: '再考虑下',
        confirmText: '取消订单',
        content: '订单还未付款，确认取消吗？',
        confirmColor: '#1AAD16',
        success: function (res) {
          if (res.confirm) {
            //发起请求，获取列表列表
            wx.showToast({
              title: '加载中',
              icon: 'loading',
              mask: true,
              duration: 10000
            });
            wx.request({
              url: app.globalData.requestUrl,
              data: {
                map: 'applet_cancel_order',
                // suid: app.globalData.suid,
                tid: orderId
              },
              success: function (res) {
                if (res.data.ec == 200) {
                  console.log(res.data.data);
                  app.errorTip(that, '订单已取消成功~', 2000);
                  that.onPullDownRefresh();
                } else {
                  wx.showModal({
                    title: '提示',
                    content: res.data.em,
                    showCancel: false
                  });
                }
              },
              complete: function () {
                wx.hideToast();
              }
            });
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    },
    seeWuliu: function (e) {
      var that = this;
      var orderId = e.target.dataset.id;
      //发起请求，获取列表列表
      wx.showToast({
        title: '加载中',
        icon: 'loading',
        mask: true,
        duration: 10000
      });
      wx.request({
        url: app.globalData.requestUrl,
        data: {
          map: 'applet_order_fetch_track',
          // suid: app.globalData.suid,
          tid: orderId
        },
        success: function (res) {
          if (res.data.ec == 200) {
            console.log(res.data.data);
            that.setData({
              modalType: 'wuliu',
              isShowModal: true,
              logisticsInfo: res.data.data
            })
          } else {
            app.errorTip(that, res.data.em, 2000);
          }
        },
        complete: function () {
          wx.hideToast();
        }
      });
    },
    hideModal: function () {
      this.setData({
        isShowModal: false
      })
    },
    remindSend: function (e) { //触发订阅消息
      var that = this;
      var curTid = e.target.dataset.id;
      that.setData({
        curTid: curTid
      })
      app.getSubId(that, 'applet_order_remind', 'toRemindSend');
    },
    toRemindSend: function (e) {
      var that = this;
      var orderId = that.data.curTid;
      //发起请求，获取列表列表
      wx.showToast({
        title: '加载中',
        icon: 'loading',
        mask: true,
        duration: 10000
      });
      wx.request({
        url: app.globalData.requestUrl,
        data: {
          map: 'applet_order_remind',
          // suid: app.globalData.suid,
          tid: orderId
        },
        success: function (res) {
          if (res.data.ec == 200) {
            console.log(res.data.data);
            app.errorTip(that, res.data.data.msg, 2000);
          } else {
            app.errorTip(that, res.data.em, 2000);
          }
        },
        complete: function () {
          wx.hideToast();
        }
      });
    },
    tkMoneyChange: function (e) {
      this.setData({
        tkMoney: e.detail.value
      })
    },
    tkReasonChange: function (e) {
      this.setData({
        tkReason: e.detail.value
      })
    },
    tkContactChange: function (e) {
      this.setData({
        tkContact: e.detail.value
      })
    },
    applyTuikuan: function (e) {
      var that = this;
      var orderId = e.target.dataset.id;
      that.setData({
        modalType: 'tuikuan',
        tkMoney: "",
        tkReason: "",
        tkContact: "",
        isShowModal: true,
        tkOrderid: orderId
      })
  
    },
    submitTkapply: function () {
      var that = this;
      app.getSubId(that, 'applet_order_refund', 'toSubmitTkapply');
    },
    toSubmitTkapply: function () {
      var that = this;
      var data = {};
      data.map = 'applet_order_refund';
      // data.suid = app.globalData.suid,
      data.tid = that.data.tkOrderid;
      data.money = that.data.tkMoney;
      data.reason = that.data.tkReason;
      data.contact = that.data.tkContact;
  
      if (data.money == "") {
        app.errorTip(that, "请输入退款金额", 2000);
      } else {
        if (data.reason == "") {
          app.errorTip(that, "请输入退款原因", 2000);
        } else {
          if (data.contact == "") {
            app.errorTip(that, "请输入您的联系方式", 2000);
          } else {
            console.log(data);
            //发起请求，获取列表列表
            wx.showToast({
              title: '加载中',
              icon: 'loading',
              mask: true,
              duration: 10000
            });
            wx.request({
              url: app.globalData.requestUrl,
              data: data,
              success: function (res) {
                if (res.data.ec == 200) {
                  console.log(res.data);
                  app.errorTip(that, res.data.data.msg, 2000);
                } else {
                  app.errorTip(that, res.data.em, 2000);
                }
              },
              complete: function () {
                that.setData({
                  isShowModal: false
                })
                wx.hideToast();
              }
            });
          }
        }
      }
    },
    confirmReceiving: function (e) { //触发订阅消息
      var that = this;
      var curTid = e.target.dataset.id;
      that.setData({
        curTid: curTid
      })
      app.getSubId(that, 'applet_order_confirm_accept', 'toConfirmReceiving');
    }, 
    toConfirmReceiving: function (e) {
      var that = this;
      var orderId = that.data.curTid;
      wx.showModal({
        title: '',
        cancelText: '还没收到',
        confirmText: '确认收货',
        content: '确认收到货物了吗？',
        confirmColor: '#1AAD16',
        success: function (res) {
          if (res.confirm) {
            //发起请求，获取列表列表
            wx.showToast({
              title: '加载中',
              icon: 'loading',
              mask: true,
              duration: 10000
            });
            wx.request({
              url: app.globalData.requestUrl,
              data: {
                map: 'applet_order_confirm_accept',
                // suid: app.globalData.suid,
                tid: orderId
              },
              success: function (res) {
                if (res.data.ec == 200) {
                  console.log(res.data.data);
                  app.errorTip(that, res.data.data.msg, 2000);
                  that.onPullDownRefresh();
                } else {
                  wx.showModal({
                    title: '提示',
                    content: res.data.em,
                    showCancel: false
                  });
                }
              },
              complete: function () {
                wx.hideToast();
              }
            });
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    },
    goodEvalute: function (e) {
      var that = this;
      var orderId = e.target.dataset.id;
      wx.navigateTo({
        url: '../evaluate/evaluate?orderid=' + orderId
      })
    },
    payorder: function (e) {
      var orderId = e.target.dataset.id;
      wx.navigateTo({
        url: '/subpages1/orderDetail/orderDetail?orderid=' + orderId
      })
    },
    extendReceiving: function (e) {
      var that = this;
      var orderId = e.target.dataset.id;
      wx.showModal({
        title: '确认延长收货时间？',
        cancelText: '取消',
        confirmText: '确认',
        content: '每个订单只能延长收货一次哦~',
        confirmColor: '#1AAD16',
        success: function (res) {
          if (res.confirm) {
            //发起请求，获取列表列表
            wx.showToast({
              title: '加载中',
              icon: 'loading',
              mask: true,
              duration: 10000
            });
            wx.request({
              url: app.globalData.requestUrl,
              data: {
                map: 'applet_order_extended_delivery',
                // suid: app.globalData.suid,
                tid: orderId
              },
              success: function (res) {
                if (res.data.ec == 200) {
                  console.log(res.data.data);
                  app.errorTip(that, res.data.data.msg, 2000);
                } else {
                  app.errorTip(that, res.data.em, 2000);
                }
              },
              complete: function () {
                wx.hideToast();
              }
            });
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
      
    },
    delOrder: function (e) {
      var that = this;
      var orderId = e.target.dataset.id;
      wx.showModal({
        title: '删除提示',
        cancelText: '取消',
        confirmText: '确认',
        content: '确认删除该订单吗',
        confirmColor: '#1AAD16',
        success: function (res) {
          if (res.confirm) {
            //发起请求，获取列表列表
            wx.showToast({
              title: '加载中',
              icon: 'loading',
              mask: true,
              duration: 10000
            });
            wx.request({
              url: app.globalData.requestUrl,
              data: {
                map: 'applet_order_delete',
                // suid: app.globalData.suid,
                tid: orderId
              },
              success: function (res) {
                if (res.data.ec == 200) {
                  console.log(res.data.data);
                  app.errorTip(that, res.data.data.msg, 2000);
                  that.onPullDownRefresh();
                } else {
                  app.errorTip(that, res.data.em, 2000);
                }
              },
              complete: function () {
                wx.hideToast();
              }
            });
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    },
    groupResult: function (e) {//拼团结果
      var that = this;
      var tid = e.target.dataset.id;
      wx.navigateTo({
        url: '/subpages1/groupResult/groupResult?tid=' + tid
      })
    },
    makeCall: function () {
      app.makeCall();
    },
    copyNumber: function (e) {
      var number = e.currentTarget.dataset.number;
      wx.setClipboardData({
        data: number,
        success: function () {
          wx.showToast({
            title: '复制成功',
          })
        },
        fail: function (res) {
          console.log(res)
        }
      })
    }
  }
})
